package com.ybliang.plat.common.rpc.registry.consul.config;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ybliang.plat.common.rpc.registry.consul.ConsulConfigProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableConfigurationProperties(value = {ConsulConfigProperties.class})
public class ConsulRegisterService implements InitializingBean, DisposableBean {

    public static Logger LOGGER = LoggerFactory.getLogger(ConsulRegisterService.class);

    @Autowired
    ConsulConfigProperties properties;

    @Override
    public void destroy() throws Exception {
        String consulNodesUrl = properties.getNodeUrl();
        for (String url : consulNodesUrl.split(",")) {
            ConsulClient client = new ConsulClient(url);
            client.agentServiceDeregister(properties.getInstanceId());
            LOGGER.info("ConsulRegisterService service:{} has deregistry from consul:{}",
                    properties.getName(),
                    url);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String instanceId = encrypt(properties.getHost() + ":" + properties.getPort());
        properties.setInstanceId(instanceId);
        NewService newService = new NewService();
        newService.setId(instanceId);
        newService.setName(properties.getName());
        newService.setAddress(properties.getHost());
        newService.setPort(properties.getPort());
        List<String> tags = new ArrayList<>();
        tags.add(properties.getVersion());
        tags.add("proto=tcp");
        newService.setTags(tags);

        NewService.Check check = new NewService.Check();
        check.setInterval(properties.getInterval() + "s");
        check.setTcp(properties.getHost() + ":" + properties.getPort());

        newService.setCheck(check);

        String consulNodesUrl = properties.getNodeUrl();
        for (String url : consulNodesUrl.split(",")) {
            ConsulClient client = new ConsulClient(url);
            Response<Void> resp = client.agentServiceRegister(newService);
            LOGGER.info("ConsulRegisterService service:{} has registry to consul:{}, resp:{}",
                    properties.getName(),
                    url,
                    resp);
        }


    }

    /**
     * MD5加密
     * @param source 加密前字符串
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encrypt(String source) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Bytes = md5.digest(source.getBytes());
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16){
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
